package com.xxxx.server.controller;

import com.xxxx.server.pojo.Admin;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.util.FastDFUtils;
import com.xxxx.server.vo.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * wsy 2021-11-29 16:11
 * 个人中心
 **/
@RestController
@RequestMapping
@Api(tags = "个人中心")
public class AdminInfoController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation("更新当前角色信息")
    @PutMapping
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities())
            );
            return new RespBean().success("更新成功");
        }
        return new RespBean().error("更新失败");
    }

    @ApiOperation("更新用户密码")
    @PutMapping("/admin/editPassword")
    public RespBean updatePassword(@RequestBody Map<String,Object> params){
        String oldPass = (String) params.get("oldPass");
        String pass = (String) params.get("pass");
        Integer adminId = Integer.parseInt((String) params.get("adminId"));
        return adminService.updateAdminPassword(oldPass,pass,adminId);
    }

    @ApiOperation("更新用户头像")
    @PostMapping
    public RespBean updateUserFace(MultipartFile file,Integer adminId,Authentication authentication){
        String[] filePath = FastDFUtils.upload(file);
        /**
         * url = http://192.168.66.66/group1/M00/00/00/wKhCQmGl90CATxb3AAIyGcz_Qsg963.png
         * FastDFUtils.getTrackerUrl() = http://192.168.66.66/
         * filePath[0] = group1
         * filePath[1] = M00/00/00/wKhCQmGl90CATxb3AAIyGcz_Qsg963.png
         */
        String url = FastDFUtils.getTrackerUrl() + filePath[0] + "/" + filePath[1];
        return adminService.updateUserFace(url,adminId,authentication);
    }
}
